package com.bua.net;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: shenran
 * Date: 13-7-1
 * Time: 时间 10:43
 * To change this template use File | Settings | File Templates.
 */
public class RequestTask implements Runnable {

    private static final int GET = 0;
    private static final int POST = 1;
    public static final int DID_START = 0;
    public static final int DID_ERROR = 1;
    public static final int DID_SUCCEED = 2;


    private URL url;
    private int method = 1;
    private HashMap<String, String> requestMap;
    private HttpClient httpClient;
    private ResponseReport report;
    private int requestId;
    private Boolean isCancle = false;

    public void CreateTask(String STRURL, HashMap<String, String> REQUEST_MAP, int REQUEST_ID, ResponseReport LISTENER) {
        try {
            url = new URL(STRURL);
            requestMap = REQUEST_MAP;
            if (NetConfig.DepartmentID != null)
                requestMap.put("DepartmentID", NetConfig.DepartmentID);
            requestMap.put("DeviceID", NetConfig.DeviceID);

            requestId = REQUEST_ID;
            report = LISTENER;
            RequestManager.getInstance().appendRequest(this);
        } catch (MalformedURLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    private static final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case RequestTask.DID_START: {
                    break;
                }
                case RequestTask.DID_SUCCEED: {
                    ResponseReport _Report = (ResponseReport) message.obj;
                    Object data = message.getData();
                    if (_Report != null) {
                        if (data != null) {
                            Bundle bundle = (Bundle) data;
                            String result = bundle.getString("callbackkey");
                            int httpRequestId = message.arg1;
                            _Report.callBack(result, httpRequestId);
                        }
                    }

                    break;
                }
                case RequestTask.DID_ERROR: {
                    break;
                }
            }
        }
    };

    @Override
    public void run() {
        //To change body of implemented methods use File | Settings | File Templates.

        try {
            HttpResponse httpResponse = null;
            switch (method) {
                case GET: {
                    //使用HttpURLConnection打开连接
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    //得到读取的内容(流)
                    InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
                    // 为输出 创建BufferedReader
                    //BufferedReader buffer = new BufferedReader(in);
                    ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(1024);

                    //使用循环来读取获得的数据
                    while (!isCancle) {
                        char[] buffer = new char[1024];
                        int pos = in.read(buffer, 0, 1024);
                        byteArrayBuffer.append(buffer, byteArrayBuffer.length(), pos);
                    }
                    //关闭InputStreamReader
                    in.close();
                    //关闭http连接
                    urlConn.disconnect();
                    if (!isCancle && byteArrayBuffer.length() > 0) {

                        this.sendMessage(Base64.encodeToString(byteArrayBuffer.toByteArray(), Base64.DEFAULT));
                    } else {
                        this.sendMessage("fail");
                    }
                }
                break;
                case POST: {
                    httpClient = getHttpClient();

                    HttpPost httpPost = new HttpPost(url.toURI());

                    List<NameValuePair> params = new ArrayList<NameValuePair>();

                    if (requestMap != null) {
                        for (String key : requestMap.keySet()) {

                            String value = requestMap.get(key);
                            BasicNameValuePair valuesPair = new BasicNameValuePair(key, value);
                            params.add(valuesPair);
                        }
                    }
                    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
                    httpResponse = httpClient.execute(httpPost);
                    if (isHttpSuccessExecuted(httpResponse)) {
                        String result = EntityUtils.toString(httpResponse
                                .getEntity());
                        this.sendMessage(result);
                    } else {
                        this.sendMessage("fail");
                    }
                }
                break;
            }
        } catch (Exception e) {
            this.sendMessage("fail");
        }
    }

    private void sendMessage(String result) {
        Message message = Message.obtain(handler, DID_SUCCEED,
                report);
        message.arg1 = requestId;
        Bundle data = new Bundle();
        data.putString("callbackkey", result);
        message.setData(data);
        handler.sendMessage(message);
        RequestManager.getInstance().didComplete(this);
    }

    public static DefaultHttpClient getHttpClient() {
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
        HttpConnectionParams.setSoTimeout(httpParams, 20000);
        // HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

//        String proxyStr = "192.168.1.105";
//        int port = 80;
//        HttpHost httpHost = new HttpHost(proxyStr, port);
//        HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
//        httpParams.setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);


        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        return httpClient;
    }

    public static boolean isHttpSuccessExecuted(HttpResponse response) {
        int statusCode = response.getStatusLine().getStatusCode();
        return (statusCode > 199) && (statusCode < 400);
    }
}
